#include <stdio.h>
#include <stdlib.h>
//#include <malloc.h>
#include "stack1.h"

static void copyToNode(const Item item,Node *pnode);
static void copyToItem(Item *pitem,const Node *pnode);

void createStack(Stack *st)
{
	st->top = NULL;
	st->len = 0;
}

BOOL push(const Item data,Stack *st)
{
	Node *pnode;

	if (stIsFull(st))
		return FALSE;
	
	pnode = (Node *)malloc(sizeof(Node));
	if (pnode == NULL){
		fprintf(stderr,"Can't malloc memory!\n");
		return FALSE;
	}
	copyToNode(data,pnode);
	pnode->next = st->top;
	st->top = pnode;
	st->len++;
	return TRUE;
}

BOOL pop(Item *pdata,Stack *st)
{
	Node *psave;

	if (stIsEmpty(st))
		return FALSE;

	copyToItem(pdata,st->top);
	psave = st->top->next;
	free(st->top);
	st->top = psave;
	st->len--;
	return TRUE;
}

BOOL stIsEmpty(const Stack *st)
{
	return st->len == 0;
}

BOOL stIsFull(const Stack *st)
{
	return st->len == MAX_STSIZE;
}

BOOL destroyStack(Stack *st)
{
	Item temp;
	if (stIsEmpty(st))
		return FALSE;

	while(pop(&temp,st));
	return TRUE;
}

static void copyToNode(const Item item,Node *pnode)
{
	pnode->item = item;
}

static void copyToItem(Item *pitem,const Node *pnode)
{
	*pitem = pnode->item;
}

